<?php

class myUser extends sfBasicSecurityUser
{
  /**
   * Logs user into the system
   *
   * Sets cridentails and user attributes necessary to manage user session if
   * "Remember me" checkbox was checked will set a cookie
   *
   * @param object  $user          User object of user to be signed in to the system
   * @param boolean $remember      Submitted value of "remember me" field in the login form
   * @return void
   */
  public function signIn($user, $remember=false)
  {
    $this->setAuthenticated(true); 
    $this->addCredential($user->getCredential());
    
    $this->setAttribute('username', $user->getUsername(), 'subscriber');
    $this->setAttribute('user_id', $user->getId(), 'subscriber');
    
    if ($remember)
    {
      $key = sha1(myTools::makeRandomString());
      
      //save the key to db
      $user->setRemember($key);
      $user->save();
      
      // save the key to the cookie
      $value = $user->getRemember().'-'.$user->getUsername();
      $this->setUserCookie($value);      
    }  
  }
    
  /**
   * Logs user out of the system
   *
   * Destroys user session and cookies
   *
   * @return void
   */  
  public function signOut()
  {
    $this->getAttributeHolder()->removeNamespace('subscriber');
 
    $this->setAuthenticated(false);
    $this->clearCredentials();
    
    //clear the cookie
    $this->setUserCookie();        
  }
  
  /**
   * Sets user cookie
   *
   * If called with a $value will set a cookie, otherwise will set delete
   * a cookie by setting expiration date in the past
   *
   * @param boolean $value   If true will set a valid cookie else will delete existing
   * @return void
   */
  public function setUserCookie($value=false)
  {
    // if value needs to be set
    if($value)
    {
      $time = time()+60*60*24*sfConfig::get('app_cookie_timeout');
    }
    // set cookie expiration time in the past deleting the cookie
    else
    {
      $time = mktime(12, 0, 0, 1, 1, 1990);
    }
    
    if ($_SERVER['HTTP_HOST'] == 'localhost')
    {
      sfContext::getInstance()->getResponse()->setCookie(sfConfig::get('app_cookie_name'), $value, $time, '/');
    }
    else
    {
      sfContext::getInstance()->getResponse()->setCookie(sfConfig::get('app_cookie_name'), $value, $time, '/', $domain, false, false);
    } 
  }  
	
  public function getLang()
  {
    return myTools::langFromCulture($this->getCulture());
  }
  
  public function setDir($direction)
  {
    $this->setAttribute('direction', $direction, 'subscriber');
  }
  
  public function getDir()
  {
    return $this->getAttribute('direction', '', 'subscriber');
  }
  
  public function getUsername()
  {
    return $this->getAttribute('username', '', 'subscriber');
  }
  
  public function getUserId()
  {
    return $this->getAttribute('user_id', '', 'subscriber');
  }
}
